package com.servlet;

import com.dao.imp.*;
import com.entity.Address;
import com.entity.Good;
import com.entity.Order;
import com.entity.ShoppingCart;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Mathison
 * @Title: ${NAME}
 * @Package: ${PACKAGE_NAME}
 * @Description: TODO
 * @date 2021/11/28 16:29
 **/

@WebServlet(name = "CreatOrderFromCartServlet", value = "/CreatOrderFromCartServlet")
public class CreatOrderFromCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession();
        int user_id = Integer.parseInt(session.getAttribute("userId").toString());
        int address_id = Integer.parseInt(request.getParameter("shippingId"));

        String idList =  request.getParameter("idList");
        FindGoodsDaoImp findGoodsDaoImp = new FindGoodsDaoImp();
        List<Good> goodList = new ArrayList();
//        idList.split(",");
//        System.out.println(idList.split(",")[0]);
        //根据商品id获得全部商品；
        Map<String,Good> goodMap = new HashMap<>();
        for (String i:
             idList.split(",")) {
            String sql = "SELECT * FROM goods WHERE good_id="+i;
            Good good = findGoodsDaoImp.getGood(sql);
            goodMap.put(String.valueOf(good.getGood_id()),good);
        }
        JSONObject goodJson = JSONObject.fromObject(goodMap);
//        System.out.println("good json:");
//        System.out.println(goodJson);
        //根据地址id获取对应地址
        String addressSql = "SELECT * FROM address WHERE address_id="+address_id;
        List<Address> address = FindAddress.getAddress(addressSql);
        JSONArray addressJson = JSONArray.fromObject(address);

//        System.out.println("address json:");
//        System.out.println(addressJson);

        //根据goodList拿到对应的全部商品数量
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
//        for (Good good:
//             goodList) {
////            System.out.println(good.toString());
//            String cartSql = "SELECT * FROM shopingchart WHERE user_id="+user_id+" AND good_id="+good.getGood_id();
////            System.out.println(cartSql);
//            shoppingCartList.add(FindCartInfo.getCartInfo(cartSql));
//        }
        for (Good value:goodMap.values()){
            String cartSql = "SELECT * FROM shopingchart WHERE user_id="+user_id+" AND good_id="+value.getGood_id();
////            System.out.println(cartSql);
            shoppingCartList.add(FindCartInfo.getCartInfo(cartSql));
        }
//        List<Integer> orderGoodNumList = new ArrayList<>();
        Map<String,Integer> orderGoodNumList = new HashMap<>();
        for (ShoppingCart sc:
             shoppingCartList) {
            orderGoodNumList.put(String.valueOf( sc.getGood_id()),sc.getGood_amount());
        }
//        System.out.println(orderGoodNumList);

        JSONObject amountJson = JSONObject.fromObject(orderGoodNumList.toString());

//        System.out.println("amount json:");
//        System.out.println(amountJson);

        //创建订单
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String date = formatter.format(new Date(System.currentTimeMillis()));
        System.out.println(goodJson);
        String insertSql = "INSERT INTO orders (user_id, order_creatTime, good_amount, receive_address, good, status, isPay) VALUES (" +
                user_id+", \'" +
                date+"\', \'" +
                amountJson +"\', \'" +
                addressJson.get(0)+"\', \'" +
                goodJson+"\', " +
                "DEFAULT,DEFAULT)";

        AddUpdDelDaoImp addUpdDelDaoImp = new AddUpdDelDaoImp();
        addUpdDelDaoImp.addUpdDelGoods(insertSql);
//        AND good_amount=\'"+amountJson+"\'
        String orderSql = "SELECT * FROM orders WHERE user_id="+user_id+" AND order_creatTime=\'"+date+"\'";

//        System.out.print("orderSql:");
//        System.out.println(orderSql);

        Order order = FindOrder.getOrderInfo(orderSql);

//        System.out.println(order.getOrder_id());

        JSONObject json = JSONObject.fromObject("{order_id:"+order.getOrder_id()+"}");
        response.getWriter().print(json);

    }
}
